﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using Facebook;

namespace WpfApplication1
{

    public partial class LoginForm : Form
    {
        private Uri _loginUri;
        public FacebookOAuthResult _FacebookOAuthResult;
        public FacebookOAuthResult FacebookOAuthResult { get { return _FacebookOAuthResult;}}
        public string AccessToken;
        public LoginForm(string appId, string permission)
        {
            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            FacebookOAuthClient oauthClient = new FacebookOAuthClient { AppId = appId };
            IDictionary<string, object> loginParameters = new Dictionary<string, object>();

            loginParameters["response_type"] = "token";
            loginParameters["display"] = "popup";

            if (!string.IsNullOrEmpty(permission))
            {
                // A comma-delimited list of permissions
                loginParameters["scope"] = permission;
            }
            _loginUri = oauthClient.GetLoginUrl(loginParameters);
            // Đã lấy được login url

            InitializeComponent();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            mainBrower.Navigate(_loginUri);
        }

        private void mainBrower_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            FacebookOAuthResult oauthResult;
            if (FacebookOAuthResult.TryParse(e.Url, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication.
                _FacebookOAuthResult = oauthResult;
                AccessToken = oauthResult.AccessToken;
                if (_FacebookOAuthResult == null)
                    MessageBox.Show("null rui");
                if (_FacebookOAuthResult.IsSuccess)
                    this.DialogResult = DialogResult.OK;
                else
                    this.DialogResult = DialogResult.No;
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
                this._FacebookOAuthResult = null;
            }
        }
    }
}
